//
//  InfoViewController.m
//  IBaby
//
//  Created by ZengYuan on 14/11/26.
//  Copyright (c) 2014年 com.zhongwei. All rights reserved.
//

#import "InfoViewController.h"
#import "ShowSetCell.h"
//#import "ModifyPasswdViewController.h"
#import "UserUnit.h"
//#import "HeaderSettingCell.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>

//#import "QiniuSDK.h"
#import "CameraEngine.h"
#import "AppDelegate.h"
#import "HeaderSettingCell.h"
#import "InputNameTextViewController.h"

//#import "BabyManager.h"
//#import "RegexKitLite.h"

@interface InfoViewController ()<CameraEngineDelegate,UIActionSheetDelegate>
{
    CameraEngine *cameraEngine;
    UIImage *pickedHeaderImage;
}
@end

@implementation InfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = MAIN_DARKCOLOR;
    
    CGRect rect = self.view.bounds;
    rect.size.height -=self.navigationController.navigationBar.frame.size.height+(OSVersionIsAtLeastiOS7?20:0);
    
    tableView = [[UITableView alloc]initWithFrame:rect style:UITableViewStylePlain];
    tableView.delegate=self;
    tableView.dataSource=self;
    tableView.backgroundColor=[UIColor clearColor];
    tableView.backgroundView = nil;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:tableView];
    
//    UIWindow *window=[[UIApplication sharedApplication].windows lastObject];
//    hud=[MBProgressHUD showHUDAddedTo:window animated:YES];
//    hud.mode = MBProgressHUDModeIndeterminate;
//    hud.labelText=@"加载中...";
 
    
    dataArray=[NSArray arrayWithObjects:
    
               [NSArray arrayWithObjects:@"头像", nil],
                [NSArray arrayWithObjects:@"姓名",nil],
//                        [NSArray arrayWithObjects:@"注销账号", nil],
                       nil];

    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    self.titleLabel.text=@"个人信息";
    userUnit=[UserUnit getActiveUser];

    [tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataArray[section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}

- (UIView *)tableView:(UITableView *)_tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 20)];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 82;
    }
    
    return 55;
    ;
}

- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 
        //头像
        if(indexPath.section==0){
            static NSString *CellHeaderId = @"CellHeader";
            HeaderSettingCell *headCell = [_tableView dequeueReusableCellWithIdentifier:CellHeaderId];

            if (!headCell) {
                headCell=[[HeaderSettingCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellHeaderId];
//                headCell.arrowHidden = YES;
//                headCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

             }
            NSArray *array=dataArray[indexPath.section];
            headCell.textLabel.text=[array objectAtIndex:indexPath.row];
            headCell.rowType = [self rowIndex:indexPath];

//            NSString *url = jkunit.headUrl;
//            if ([url length]) {
//                [headCell.imgView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:headCell.imgView.image];
//            }else{
                headCell.imgView.image = [UIImage imageNamed:@"head"];
//            }
            

            return headCell;
        }
        
        else if(indexPath.section==1){
            
            static NSString *CellActivity = @"CellActivity";
            ShowSetCell *cell=[_tableView dequeueReusableCellWithIdentifier:CellActivity];
            if (!cell) {
                cell=[[ShowSetCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellActivity];
                cell.textLabel.font=[UIFont systemFontOfSize:14];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
//            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

            NSArray *array=dataArray[indexPath.section];
            cell.textLabel.text=[array objectAtIndex:indexPath.row];
            cell.rowType = [self rowIndex:indexPath];
 

            if (indexPath.row==0) {
                cell.contentLabel.text = userUnit.userName;
                NSLog(@"userUnit.userName = %@", userUnit.userName);
            }
         
            return cell;
            
        }
    
    return nil;
}

-(int)rowIndex:(NSIndexPath *)indexPath{
    int result = 0;
    
    NSInteger rowsCount = [dataArray[indexPath.section] count];
    
    if (rowsCount>1) {
        if (indexPath.row==0) {
            result= 1;
        }else if(indexPath.row == rowsCount-1){
            result= 3;
        }else{
            result= 2;
        }
    }else{
        result= 0;
    }
    
    return result;
}

-(NSString *)sexTranslate:(NSString *)str{
    if([str isEqualToString:@"M"] || [str isEqualToString:@"m"] ){
        return @"男";
    }else  if([str isEqualToString:@"F"] || [str isEqualToString:@"f"] ){
        return @"女";
    }else{
        return nil;
    }

}

- (void)tableView:(UITableView *)atableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    selectedIndexPath=indexPath;

        if (indexPath.section == 1) {
            if (indexPath.row == 0) {
                //修改姓名
                [self openInput];
            }
            
            
        }

    
}

-(void)openInput{
    
    InputNameTextViewController *ivc = [[InputNameTextViewController alloc]init];
    ivc.originalText = userUnit.userName;
    [self.navigationController pushViewController:ivc animated:YES];
    
}

-(void)openHeaderPicker{
    //检查相机是否可用
    if (OSVersionIsAtLeastiOS7) {
        NSString *mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        if (authStatus == AVAuthorizationStatusDenied) {
            
            UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:nil message:@"请前往系统设置->隐私->相机，开启爱维宝贝权限" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            return;
        }
        
    }
    
    
    //检查相册是否可用
    if (OSVersionIsAtLeastiOS7) {
        ALAuthorizationStatus authStatus = [ALAssetsLibrary authorizationStatus];
        if (authStatus == ALAuthorizationStatusDenied) {
            
            UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:nil message:@"请前往系统设置->隐私->相片，开启爱维宝贝权限" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            return;
        }
   
    }
    
    if(OSVersionIsAtLeastiOS8){
        UIAlertController*alertController = [UIAlertController
                                             alertControllerWithTitle:@"设置头像" message:nil
                                             preferredStyle:UIAlertControllerStyleActionSheet];
        
        // Create the actions.
        UIAlertAction*takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction*action) {
            
            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                MBALERT(@"您的设备不支持摄像头");
                return;
            }
            
            if (!cameraEngine) {
                cameraEngine = [[CameraEngine alloc]init];
                cameraEngine.delegate=self;
            }
            
            [cameraEngine startCameraTakePhoto:self];
            
        }];
        
        UIAlertAction*pickLibraryAction = [UIAlertAction actionWithTitle:@"打开相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction*action) {
            NSLog(@"Okay");
            
            if (!cameraEngine) {
                cameraEngine = [[CameraEngine alloc]init];
                cameraEngine.delegate=self;
            }
            
            [cameraEngine openPhotoAlbum:self editable:YES];
        }];
        
        
        UIAlertAction*cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction*action) {
            
        }];
        
        // Add the actions.
        [alertController addAction:takePhotoAction];
        [alertController addAction:pickLibraryAction];
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        
        UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"设置头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"打开相册",nil];
        [actionSheet showInView:self.view];
        
        
    }
    
}

#pragma mark  UIActionSheetDelegate -

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex==0) {
        if (!cameraEngine) {
            cameraEngine = [[CameraEngine alloc]init];
            cameraEngine.delegate=self;
        }
        
        [cameraEngine startCameraTakePhoto:self];
    }else if (buttonIndex == 1) {
        if (!cameraEngine) {
            cameraEngine = [[CameraEngine alloc]init];
            cameraEngine.delegate=self;
        }
        
        [cameraEngine openPhotoAlbum:self editable:YES];
    }
}

#pragma mark CameraEngine -
-(void)CameraDidTakePhotoFinished:(UIImage *)_img{
    
    Reachability*rea= [Reachability reachabilityForInternetConnection];
    if (![rea isReachable]){
        MBALERT(HTTPERROR_CANNOTREACH);
        return;
    }
    
    UIWindow *window=[[UIApplication sharedApplication].windows lastObject];
    hud=[MBProgressHUD showHUDAddedTo:window animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.labelText=@"头像上传中";
    
    
    pickedHeaderImage=_img;
//    [self upload:_img];
}

-(void)CameraDidChosePhotoFromAlbum:(UIImage *)_img{
    
    Reachability*rea= [Reachability reachabilityForInternetConnection];
    if (![rea isReachable]){
        MBALERT(HTTPERROR_CANNOTREACH);
        return;
    }
    
    UIWindow *window=[[UIApplication sharedApplication].windows lastObject];
    hud=[MBProgressHUD showHUDAddedTo:window animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.labelText=@"头像上传中";
    
    pickedHeaderImage=_img;
//    [self upload:_img];

    
}


-(void)CameraFailed:(int)_code Err:(NSString *)errormsg{
    MBALERT(errormsg);
}

-(void)CameraCanceled{
    
}



#pragma mark - 输入框

-(NSString *)inputAlertTitle{
    if (selectedIndexPath.section == 1 && selectedIndexPath.row == 0) {
        return @"输入您的姓名";
    }
    
    if (selectedIndexPath.section ==1 && selectedIndexPath.row == 3) {
        return @"输入您的邮箱";
    }
    
    return @"";
}


@end
